﻿using LiteDb;
using LiteDB;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteDb
{
    public class MqttFormatJson
    {
        public const string CollectionName = nameof(MqttFormatJson);
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public int GroupDeviceId { get; set; }
        public string Extra { get; set; } = string.Empty;
    }

    public class MqttFormatJsonRepository
    {
        private readonly ILiteCollection<MqttFormatJson> _collection;
        private const int customId = 2008;// 协议偏移
        
        public MqttFormatJsonRepository(LiteDatabase db)
        {
            _collection = db.GetCollection<MqttFormatJson>(MqttFormatJson.CollectionName);
            initDefaultData();// 初始化默认数据
        }

        private void initDefaultData()
        {
            var jsonString = @"
            {
                 ""id"":-1,
                 ""name"":""自定义类型"",
                 ""groupDeviceId"":-1,
                 ""extra"":{
                                ""publishSchemaFile"":{""data"":""{}"",""fileName"":""pub1.json""},
                                ""publishSchemaOriginFile"":{""data"":""{\""root\"":{\""type\"":\""object\"",\""title\"":\""\"",\""properties\"":{}}}"",""fileName"":""tab1_pub.json""},
                                ""subscribeSchemaFile"":{""data"":""{}"",""fileName"":""sub1.json""},
                                ""subscribeSchemaOriginFile"":{""data"":""{\""root\"":{\""type\"":\""object\"",\""title\"":\""\"",\""properties\"":{}}}"",""fileName"":""tab1_sub.json""}
                               }
             }";
            var jObject = JObject.Parse(jsonString);

            MqttFormatJson mqttFormatJson = new MqttFormatJson();
            mqttFormatJson.Name = jObject.TryGetValue("name", out var nameToken) ? nameToken.ToString() : "";
            mqttFormatJson.GroupDeviceId = jObject.TryGetValue("group_device_id", out var groupDeviceIdToken) ? groupDeviceIdToken.Value<int>() : 0;
            mqttFormatJson.Extra = jsonString;

            // 检查在同一个分组设备下是否已存在相同名称的端口
            var existingMqttFormatJson = _collection.FindOne(p => p.GroupDeviceId == mqttFormatJson.GroupDeviceId && p.Name == mqttFormatJson.Name);
            if (existingMqttFormatJson == null)
            {
                mqttFormatJson.Id = _collection.Insert(mqttFormatJson);
                jObject["id"] = mqttFormatJson.Id;
                mqttFormatJson.Extra = jObject.ToString();
                _collection.Update(mqttFormatJson);// 需要重新id的字段
            }
        }

        public object Insert(object param)
        {
            try
            {
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);

                MqttFormatJson mqttFormatJson = new MqttFormatJson();
                mqttFormatJson.Name = jObject.TryGetValue("name", out var nameToken) ? nameToken.ToString() : "";
                mqttFormatJson.GroupDeviceId = jObject.TryGetValue("group_device_id", out var groupDeviceIdToken) ? groupDeviceIdToken.Value<int>() : 0;
                mqttFormatJson.Extra = jsonString;

                // 检查在同一个分组设备下是否已存在相同名称的端口
                var existingMqttFormatJson = _collection.FindOne(p => p.GroupDeviceId == mqttFormatJson.GroupDeviceId && p.Name == mqttFormatJson.Name);
                if (existingMqttFormatJson != null)
                {
                    return ApiResponse.Fail("插入失败: 数据已存在");
                }

                mqttFormatJson.Id = _collection.Insert(mqttFormatJson);
                jObject["id"] = mqttFormatJson.Id;
                mqttFormatJson.Extra = jObject.ToString();
                _collection.Update(mqttFormatJson);// 需要重新id的字段

                return ApiResponse.Success(mqttFormatJson.Extra);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("插入失败: " + ex.Message);
            }
        }
        public object FindById(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);
                var result = _collection.FindById(id);
                if (result == null)
                    return ApiResponse.Fail("未找到数据", null, ApiResponseCode.NotFound);
                return ApiResponse.Success(result);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object FindAll(object param)
        {
            try
            {
                List<MqttFormatJson> list;

                if (param != null)
                {
                    // 根据分组设备ID过滤端口  
                    int groupDeviceId = Convert.ToInt32(param);
                    list = _collection.Find(p => p.GroupDeviceId == groupDeviceId).ToList();
                }
                else
                {
                    // 如果没有传入参数，获取所有端口  
                    list = _collection.FindAll().ToList();
                }

                // 转换为JSON数组格式
                var objectArray = list.Select(p => new
                {
                    id = p.Id,
                    name = p.Name,
                    groupDeviceId = p.GroupDeviceId,
                    extra = p.Extra
                }).ToArray();

                // 序列化为JSON字符串然后反序列化为动态对象，确保返回纯JSON格式
                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(objectArray);

                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }

        public object Update(object param)
        {
            try
            {
                MqttFormatJson mqttFormatJson = new MqttFormatJson();
                var jsonString = param.ToString()!;
                var jObject = JObject.Parse(jsonString);

                // 解析ID
                if (!jObject.TryGetValue("id", out var idToken))
                {
                    return ApiResponse.Fail("更新失败: 缺少ID字段");
                }
                mqttFormatJson.Id = idToken.Value<int>();
                mqttFormatJson.Name = jObject.TryGetValue("name", out var nameToken) ? nameToken.ToString() : "";
                mqttFormatJson.GroupDeviceId = jObject.TryGetValue("group_device_id", out var groupDeviceIdToken) ? groupDeviceIdToken.Value<int>() : 0;
                mqttFormatJson.Extra = jsonString;

                // 检查在同一个分组设备下是否已存在相同名称的端口（排除当前更新的记录）
                var existingMqttFormatJson = _collection.FindOne(p => p.GroupDeviceId == mqttFormatJson.GroupDeviceId && p.Name == mqttFormatJson.Name && p.Id != mqttFormatJson.Id);
                if (existingMqttFormatJson != null)
                {
                    return ApiResponse.Fail("更新失败: 数据已存在");
                }

                bool ok = _collection.Update(mqttFormatJson);
                return ok ? ApiResponse.Success(mqttFormatJson.Extra, "更新成功") : ApiResponse.Fail("更新失败", ok);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("更新异常: " + ex.Message);
            }
        }
        public object Delete(object param)
        {
            try
            {
                int id = Convert.ToInt32(param);

                // 先检查端口是否存在
                var mqttFormatJson = _collection.FindById(id);
                if (mqttFormatJson == null)
                {
                    return ApiResponse.Fail("删除失败: 数据不存在");
                }

                // 删除端口
                bool ok = _collection.Delete(id);

                if (ok)
                {
                    return ApiResponse.Success(ok, $"删除成功");
                }
                else
                {
                    return ApiResponse.Fail("删除失败: 数据删除失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("删除异常: " + ex.Message);
            }
        }
        public object GetByGroupId(object param)
        {
            try
            {
                int groupId = Convert.ToInt32(param);
                var list = _collection.FindAll().Where(p => p.GroupDeviceId == groupId).ToList();
                return ApiResponse.Success(list);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }
        public object FindAllMqttFormatList(object param)
        {
            try
            {
                List<MqttFormatJson> list = _collection.FindAll().ToList();

                List<string> nameList = new List<string>();
                // 需要将list转换为json数组
                var jsonArray = list.Select(p => new
                {
                    id = p.Id,
                    name = p.Name
                }).ToArray();

                string name = "";
                jsonArray = jsonArray.OrderBy(p => p.id).ToArray(); // 修复：将ToList()改为ToArray()
                for (int i = 0; i < jsonArray.Length; i++)
                {
                    name = (customId + i).ToString() + ":" + jsonArray[i].name;
                    nameList.Add(name);
                }

                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(nameList);
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }

        public Dictionary<string,int> FindAllMqttFormatListByOrderDict()
        {
            try
            {
                List<MqttFormatJson> list = _collection.FindAll().ToList();
                Dictionary<string,int> dict = new Dictionary<string,int>();
                // 需要将list转换为json数组
                var jsonArray = list.Select(p => new
                {
                    id = p.Id,
                    name = p.Name,
                }).ToArray();

                string name = "";
                jsonArray = jsonArray.OrderBy(p => p.id).ToArray(); // 修复：将ToList()改为ToArray()
                for (int i = 0; i < jsonArray.Length; i++)
                {
                    name = (customId + i).ToString() + ":" + jsonArray[i].name;
                    dict.Add(name, customId + i);
                }
                return dict;
            }
            catch (Exception)
            {
                return new Dictionary<string,int>();
            }
        }

        public object FindAllMqttFormatListByOrder(object param)
        {
            try
            {
                List<MqttFormatJson> list = _collection.FindAll().ToList();

                List<MqttFormatJson> listOrder = new List<MqttFormatJson>();
                // 需要将list转换为json数组
                var jsonArray = list.Select(p => new
                {
                    id = p.Id,
                    name = p.Name,
                    extra = p.Extra
                }).ToArray();

                jsonArray = jsonArray.OrderBy(p => p.id).ToArray(); // 修复：将ToList()改为ToArray()
                for (int i = 0; i < jsonArray.Length; i++)
                {
                    MqttFormatJson mqttFormatJson = new MqttFormatJson
                    {
                        Id = customId + i,
                        Name = jsonArray[i].name,
                        Extra = jsonArray[i].extra
                    };
                    listOrder.Add(mqttFormatJson);
                }

                var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(listOrder);
                return ApiResponse.Success(jsonString);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail("查询失败: " + ex.Message);
            }
        }

    }
}
